package top.hmtools.configurationManager;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PreDestroy;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import top.hmtools.cssManager.CssController;
import top.hmtools.cssManager.CssManagerDefault;
import top.hmtools.cssManager.ICssManager;
import top.hmtools.jsManager.IJavascriptManager;
import top.hmtools.jsManager.JavascriptController;
import top.hmtools.jsManager.JavascriptManagerDefault;

/**
 * 自动配置类，本jar包被其它spring boot 工程引用时的入口启动（初始化）程序
 * @author HyboJ
 * 创建日期：2017-9-26下午7:51:58
 */
@Configuration
@ConditionalOnClass({IJavascriptManager.class,ICssManager.class})//当spring容器中有 IJavascriptManager.class,ICssManager.class 的对象实例时，进行本对象实例初始化
@EnableConfigurationProperties(JsCssProperties.class)//使用JsCssProperties.class配置类
@ConditionalOnProperty(prefix = "hm_tools.js_css", value = "enabled", matchIfMissing = true)//当配置文件中有hm_tools.js_css.enabled=false时，则不创建本类中的bean，如果为hm_tools.js_css.enabled=true，或者没有该条配置（注解默认为true），则创建bean
public class JsCssAutoConfiguration {
	
	protected final Logger logger = LoggerFactory.getLogger(JsCssAutoConfiguration.class);
	
	@Autowired
	private JsCssProperties jsCssProperties;
	
	@Autowired  
    private RequestMappingHandlerMapping requestMappingHandlerMapping;
	
	private IJavascriptManager javascriptManager;
	
	private ICssManager cssManager;
	
	/**
	 * 销毁前执行
	 */
	@PreDestroy
	public void destroy(){
		logger.info("销毁前执行》》》》》》");
		if(this.javascriptManager != null){
			this.javascriptManager.destory();
		}
		if(this.cssManager != null){
			this.cssManager.destory();
		}
		logger.info("销毁前执行完毕！！再见~~");
	}
	
	/**
	 * 实例化接收css相关请求的controller bean
	 * @return
	 */
	@Bean
	public CssController cssController(){
		return new CssController();
	}
	
	@Bean
	public ICssManager cssManager(CssController cssController){
		//初始化css管理者
		this.cssManager = new CssManagerDefault();
		List<File> filePaths = new ArrayList<File>();
		String css_files_paths = this.getCss_files_paths();
		String[] css_files_paths_arr = css_files_paths.split(",");
		for(String pathStrTmp:css_files_paths_arr){
			File pathTmp = new File(pathStrTmp);
			if(pathTmp.isDirectory()){
				filePaths.add(pathTmp);
			}else{
				continue;
			}
		}
		this.cssManager.init(filePaths, this.getEncoding());
		
		//初始化 cssController，并绑定URL映射
		try {
			//注册绑定获取合并css文件内容的URL
			PatternsRequestCondition patternsGetCss = new PatternsRequestCondition("/"+this.getCss_uri());
			RequestMappingInfo infoGetCss = new RequestMappingInfo(patternsGetCss, null, null, null, null, null, null);
			Method methodGetCSS = cssController.getClass().getMethod("getCss", HttpServletRequest.class,HttpServletResponse.class);
			requestMappingHandlerMapping.registerMapping(infoGetCss, cssController, methodGetCSS);
			
			//注册绑定刷新css内容缓存的URL
			PatternsRequestCondition patternsRefreshCss = new PatternsRequestCondition("/"+this.getRefresh_css_uri());
			RequestMappingInfo infoRefreshCss = new RequestMappingInfo(patternsRefreshCss, null, null, null, null, null, null);
			Method methodRefreshCSS = cssController.getClass().getMethod("refreshCss", HttpServletRequest.class,HttpServletResponse.class);
			requestMappingHandlerMapping.registerMapping(infoRefreshCss, cssController, methodRefreshCSS);
			
			//注册绑定获取css内容缓存所有文件名列表的URL
			PatternsRequestCondition patternsListCss = new PatternsRequestCondition("/"+this.getList_css_uri());
			RequestMappingInfo infoListCss = new RequestMappingInfo(patternsListCss, null, null, null, null, null, null);
			Method methodListCSS = cssController.getClass().getMethod("listCssMenu", HttpServletRequest.class,HttpServletResponse.class);
			requestMappingHandlerMapping.registerMapping(infoListCss, cssController, methodListCSS);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		
		return this.cssManager;
	}
	
	/**
	 * 实例化接收javascript相关请求的controller bean
	 * @return
	 */
	@Bean
	public JavascriptController javascriptController(){
		return new JavascriptController();
	}
	
	/**
	 * 实例化javascript相关操作管理者实例
	 * @param javascriptController
	 * @return
	 */
	@Bean
	public IJavascriptManager javascriptManager(JavascriptController javascriptController){
		//初始化javascript文件管理者
		this.javascriptManager = new JavascriptManagerDefault();
		List<File> filePaths = new ArrayList<File>();
		String js_files_paths = this.getJs_files_paths();
		String[] js_files_paths_arr = js_files_paths.split(",");
		for(String pathStrTmp : js_files_paths_arr){
			File pathTmp = new File(pathStrTmp);
			if(pathTmp.isDirectory()){
				filePaths.add(pathTmp);
			}else{
				continue;
			}
		}
		javascriptManager.init(filePaths, this.getEncoding());
		
		// 初始化接收获取合并javascript文件内容的controller，并从配置文件中取请求uri进行绑定映射	this.requestMappingHandlerMapping.toString();
		try {
			//注册绑定获取合并js文件内容的URL
			PatternsRequestCondition patternsGetJs = new PatternsRequestCondition("/"+this.getJs_uri());
			RequestMappingInfo infoGetJs = new RequestMappingInfo(patternsGetJs, null, null, null, null, null, null);
			Method methodGetJS = javascriptController.getClass().getMethod("getJS", HttpServletRequest.class,HttpServletResponse.class);
			requestMappingHandlerMapping.registerMapping(infoGetJs, javascriptController, methodGetJS);
			
			//注册绑定刷新js内容缓存的URL
			PatternsRequestCondition patternsRefreshJs = new PatternsRequestCondition("/"+this.getRefresh_js_uri());
			RequestMappingInfo infoRefreshJs = new RequestMappingInfo(patternsRefreshJs, null, null, null, null, null, null);
			Method methodRefreshJs = javascriptController.getClass().getMethod("refreshJS", HttpServletRequest.class,HttpServletResponse.class);
			requestMappingHandlerMapping.registerMapping(infoRefreshJs, javascriptController, methodRefreshJs);
			
			//注册绑定获取js内容缓存文件名列表的URL
			PatternsRequestCondition patternsListJs = new PatternsRequestCondition("/"+this.getList_js_uri());
			RequestMappingInfo infoListJs = new RequestMappingInfo(patternsListJs, null, null, null, null, null, null);
			Method methodListJs = javascriptController.getClass().getMethod("listJsMenu", HttpServletRequest.class,HttpServletResponse.class);
			requestMappingHandlerMapping.registerMapping(infoListJs, javascriptController, methodListJs);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		
		return javascriptManager;
	}
	
	
	
	//#############		getter and setter	##################

	/**
	 * 获取合并后javascript文件的请求uri
	 * @return
	 */
	public String getJs_uri() {
		return this.jsCssProperties.getJs_uri();
	}

	public void setJs_uri(String js_uri) {
		this.jsCssProperties.setJs_uri(js_uri);
	}

	public String getCss_uri() {
		return this.jsCssProperties.getCss_uri();
	}

	public void setCss_uri(String css_uri) {
		this.jsCssProperties.setCss_uri(css_uri);
	}
	
	public String getRefresh_js_uri() {
		return this.jsCssProperties.getRefresh_js_uri();
	}

	public void setRefresh_js_uri(String refresh_js_uri) {
		this.jsCssProperties.setRefresh_js_uri(refresh_js_uri);
	}

	public String getRefresh_css_uri() {
		return this.jsCssProperties.getRefresh_css_uri();
	}

	public void setRefresh_css_uri(String refresh_css_uri) {
		this.jsCssProperties.setRefresh_css_uri(refresh_css_uri);
	}

	public String getJs_files_paths() {
		return this.jsCssProperties.getJs_files_paths();
	}

	public void setJs_files_paths(String js_files_paths) {
		this.jsCssProperties.setJs_files_paths(js_files_paths);
	}

	public String getCss_files_paths() {
		return this.jsCssProperties.getCss_files_paths();
	}

	public void setCss_files_paths(String css_files_paths) {
		this.jsCssProperties.setCss_files_paths(css_files_paths);
	}
	
	/**
	 * 获取字符编码格式名称
	 * @return
	 */
	public String getEncoding() {
		return this.jsCssProperties.getEncoding();
	}

	/**
	 * 设置字符编码
	 * @param encoding
	 */
	public void setEncoding(String encoding) {
		this.jsCssProperties.setEncoding(encoding);
	}
	
	public String getList_js_uri() {
		return this.jsCssProperties.getList_js_uri();
	}

	public void setList_js_uri(String list_js_uri) {
		this.jsCssProperties.setList_js_uri(list_js_uri);
	}

	public String getList_css_uri() {
		return this.jsCssProperties.getList_css_uri();
	}

	public void setList_css_uri(String list_css_uri) {
		this.jsCssProperties.setList_css_uri(list_css_uri);
	}
}
